#include "be_frame_limiter.h"

BeFrameLimiter::BeFrameLimiter()
{
	settings = Settings::Instance();
// 	t = Timer::Instance();

	active		= Settings::Instance()->getCVarPtr("fpslimit");;
	optimal		= Settings::Instance()->getCVarPtr("fpslimit_frames");
	stepsize	= 20;
	sleeptime	= 0;
	cps		= *optimal;

	timeSinceLastRender = 1.0f;
}

void BeFrameLimiter::mark(Timer *t)
{
	if ( *active )
	{
		if ( t->elapsed == 0 ) cps = 1000;
		else cps = t->bullet_ms;
	
		if ( cps > *optimal ) sleeptime += stepsize;
		else if ( cps < *optimal )
		{
			if ( sleeptime >= stepsize )	sleeptime -= stepsize;
			else 				sleeptime = 0;
		}
// 		if (sleeptime > 0 ) usleep(sleeptime);
		if (sleeptime > 0 ) SDL_Delay(sleeptime*0.01f);
	}
}

// bool BeFrameLimiter::isRenderTime()
// {
// 	if ( *active )
// 		return true;
// 
// 	timeSinceLastRender += t->elapsed;
// 	if ( timeSinceLastRender >= (1.0f / *optimal ) )
// 	{
// 		timeSinceLastRender = 0.0f;
// 		return true;
// 	}
// 
// //  	cerr << "returning false" << endl;
// 	return false;
// }

void BeFrameLimiter::swap()
{
// 	active =! active;
}

BeFrameLimiter::~BeFrameLimiter()
{
}
